package com.example.myproject.jackson;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.DeserializationContext;

import java.io.IOException;

/**
 * Created by xi on 2018/9/23.
 */
public class JacksonFloatDeSerializer extends NewPrimitiveOrWrapperDeserializer<Float> {
    private static final long serialVersionUID = 1L;
    public JacksonFloatDeSerializer(){
        this(Float.TYPE, null);
    };
    public JacksonFloatDeSerializer(Class<Float> cls, Float nvl) {
        super(cls, nvl, null);
    }
    @Override
    public Float deserialize(JsonParser p, DeserializationContext ctxt) throws IOException
    {
        return _parseFloat(p, ctxt);
    }

    protected final Float _parseFloat(JsonParser p, DeserializationContext ctxt)
            throws IOException
    {
        // We accept couple of different types; obvious ones first:
        JsonToken t = p.getCurrentToken();

        if (t == JsonToken.VALUE_NUMBER_FLOAT ||
                t == JsonToken.VALUE_NUMBER_INT) { // coercing should work too
            return p.getFloatValue();
        }
        // And finally, let's allow Strings to be converted too
        if (t == JsonToken.VALUE_STRING) {
            String text = p.getText().trim();
            if ((text.length() == 0)) {
                return UpdateSpecialConstant.FLOAT_SPECAIL_VALUE;
               // return (Float) _coerceEmptyString(ctxt, _primitive);
            }
            if (_hasTextualNull(text)) {
                return (Float) _coerceTextualNull(ctxt, _primitive);
            }
            switch (text.charAt(0)) {
                case 'I':
                    if (_isPosInf(text)) {
                        return Float.POSITIVE_INFINITY;
                    }
                    break;
                case 'N':
                    if (_isNaN(text)) {
                        return Float.NaN;
                    }
                    break;
                case '-':
                    if (_isNegInf(text)) {
                        return Float.NEGATIVE_INFINITY;
                    }
                    break;
            }
            _verifyStringForScalarCoercion(ctxt, text);
            try {
                return Float.parseFloat(text);
            } catch (IllegalArgumentException iae) { }
            return (Float) ctxt.handleWeirdStringValue(_valueClass, text,
                    "not a valid Float value");
        }
        if (t == JsonToken.VALUE_NULL) {
            return (Float) _coerceNullToken(ctxt, _primitive);
        }
        if (t == JsonToken.START_ARRAY) {
            return _deserializeFromArray(p, ctxt);
        }
        // Otherwise, no can do:
        return (Float) ctxt.handleUnexpectedToken(_valueClass, p);
    }
}
